package com.jinzhi.sys.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.domain.vo.UserDetailDO;
import com.jinzhi.jzapi.domain.vo.UserRoleVO;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.param.UserQuery;
import com.jinzhi.jzweb.domain.vo.AuntUserVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.sys.vo.UserVO;
import com.jinzhi.wxmp.service.MpConfigService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * 用户管理
 * </pre>
 * <p>
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
@Slf4j
public class UserController extends BaseController {
    private String prefix = "sys/user";
    @Autowired
    JazUserAuntService jazUserAuntService;
    @Autowired
    JazUserDemandService jazUserDemandService;
    @Autowired
    JazUserOrderService jazUserOrderService;
    @Autowired
    JazUserRechargeService jazUserRechargeService;
    @Autowired
    JazSysContractService jazSysContractService;
    @Autowired
    JazUserCommentService jazUserCommentService;
    @Autowired
    JazSysLabelService jazSysLabelService;
    @Autowired
    JazSysProjectService jazSysProjectService;
    @Autowired
    JazSysBannerService jazSysBannerService;
    @Autowired
    JazUserIntegralService jazUserIntegralService;
    @Autowired
    JazUserCollectService jazUserCollectService;
    @Autowired
    JazUserSignInService jazUserSignInService;

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    DictService dictService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private MpConfigService mpConfigService;

    @Autowired
    private DictService sysDictService;


    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @Log(value = "用户正常禁用状态",sysModule = 1,operationType = 3)
    @ResponseBody
    @PostMapping("/condition")
    @RequiresPermissions("jzweb:jazSysProject:edit")
    public Result<String> condition( UserDO userDO){
        UserDO userDO1 = userService.selectById(userDO.getId());
        //正常
        if(userDO.getStatus().equals(1)){
            userDO1.setStatus(1);
        }
        //禁用
        if(userDO.getStatus().equals(0)){
            userDO1.setStatus(0);
        }
        boolean b = userService.updateById(userDO1);
        return b ? Result.ok() : Result.fail();
    }


    @RequiresPermissions("sys:user:user")
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserDO>> list(UserDO userDTO,int pageNumber,int pageSize) {
        Wrapper<UserDO> wrapper = new EntityWrapper<UserDO>().orderBy("id", false);
        if (StringUtil.notEmpty(userDTO.getName())) {
            wrapper.like("name", userDTO.getName().trim());
        }
        if (StringUtil.notEmpty(userDTO.getUsername())) {
            wrapper.like("username", userDTO.getUsername().trim());
        }
        if (StringUtil.notEmpty(userDTO.getMobile())) {
            wrapper.like("mobile", userDTO.getMobile().trim());
        }
        if (StringUtil.notEmpty(userDTO.getIdNumber())) {
            wrapper.like("idNumber", userDTO.getIdNumber().trim());
        }
        if (null!=userDTO.getSex()) {
            wrapper.eq("sex", userDTO.getSex());
        }
        if (null!=userDTO.getState()) {
            wrapper.eq("state", userDTO.getState());
        }
        if (null!=userDTO.getStatus()) {
            wrapper.eq("status", userDTO.getStatus());
        }
        if (null!=userDTO.getType()) {
            wrapper.eq("type", userDTO.getType());
        }
        wrapper.notExists("SELECT 1 FROM jaz_user_aunt WHERE sys_user.id = jaz_user_aunt.sys_userid");
        Page<UserDO> page = userService.selectPage(getPage(UserDO.class), wrapper);
        return Result.ok(page);
    }


    @RequiresPermissions("sys:user:add")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.selectList(null);
        model.addAttribute("roles", roles);
        return prefix + "/add";
    }

    @Log(value = "添加用户",sysModule = 1,operationType = 1)
    @RequiresPermissions("sys:user:add")
    @PostMapping("/save")
    @ResponseBody
    Result<String> save(UserDO userDO) {
        if (userDO==null){
            return Result.fail();
        }
        // 校验手机号是否注册
        List<UserDO> userDOList = userService.selectList(null);
        boolean isMobileExist = userDOList.stream()
                .anyMatch(existingUser -> existingUser.getMobile().equals(userDO.getMobile()));
        if (isMobileExist){
            return Result.fail("手机号已注册");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        userDO.setStatus(1);
        userDO.setState(3);
        userDO.setPassword("123456");
        userDO.setType(0);
        try {
            userDO.setGmtCreate(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        userDO.setNickname(userDO.getUsername());
        //userDO.setName(userDO.getUsername());
        userService.insert(userDO);
        return Result.ok();
    }


    @RequiresPermissions("sys:user:edit")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        model.addAttribute("id", id);
        return prefix + "/edit";
    }

    @GetMapping("/selectUserById")
    @ApiOperation(value = "根据id获取user信息", notes = "根据id删除用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "id"),
    })
    @ResponseBody
    Result<UserRoleVO> selectUserById(@RequestParam("id") Long id) {
        UserRoleVO userRoleVO = new UserRoleVO();
        UserDO userDO = userService.selectById(id);
        userRoleVO.setUser(userDO);
        userRoleVO.setRole(roleService.findListStatusByUserId(id));
        return  Result.ok(userRoleVO);
    }

    @Log(value = "编辑并更新用户",sysModule = 1,operationType = 3)
    @RequiresPermissions("sys:user:edit")
    @PostMapping("/update")
    @ResponseBody
    Result<String> update(UserDO user) {
        userService.updateById(user);
        return Result.ok();
    }


    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:user:user")
    String info(@PathVariable("id") Long id, Model model) {
        UserDetailDO userDetailDO = new UserDetailDO();
//        Wrapper<JazUserRechargeDO> wrapper1 = new EntityWrapper<JazUserRechargeDO>().orderBy("id", false);
        Wrapper<JazUserIntegralDO> wrapper2 = new EntityWrapper<JazUserIntegralDO>().orderBy("id", false);

        if(id != null){
            wrapper2.eq("sys_userid", id);
        }
        UserDO userDO = userService.selectById(id);
//        List<JazUserRechargeDO> jazUserRechargeDO = jazUserRechargeService.selectList(wrapper1).stream().limit(1).collect(Collectors.toList());
//        //用户积分明细数据
//        Page<JazUserIntegralDO> page = jazUserIntegralService.selectPage(getPage(JazUserIntegralDO.class), wrapper2);
//        List list = new ArrayList();
//        for (int i = 0; i < page.getRecords().size(); i++) {
//            JazUserIntegralDO obj = (JazUserIntegralDO) page.getRecords().get(i);
//            obj.setCurrentIntegral(userDO.getCurrentPoints());
//            list.add(obj);
//        }
//        page.setRecords(list);
//        try {
//            BeanUtils.copyProperties(userDetailDO,userDO);
//            BeanUtils.copyProperties(userDetailDO,jazUserRechargeDO);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
//        userDetailDO.setJazUserIntegralDOPage(page);
        model.addAttribute("id",id);
        model.addAttribute("user", userDO);
//        model.addAttribute("page",page);
        return prefix + "/info";
    }


    @RequiresPermissions("sys:user:edit")
    @GetMapping("/integraEdit/{id}")
    String integraEdit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        return prefix + "/integraEdit";
    }


    @RequiresPermissions("sys:user:edit")
    @PostMapping("/integraUpdate")
    @ResponseBody
    Result<String> integraUpdate(@RequestParam("id") Long id,@RequestParam("integra") String integra) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        //更新用户当前积分数据
        UserDO userDO = userService.selectById(id);
        String currentPoints = userDO.getCurrentPoints();
        userDO.setCurrentPoints(integra);
        userService.updateById(userDO);
        //添加积分消费明细记录
        JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
        jazUserIntegralDO.setSysUserid(id);
        if(Integer.parseInt(currentPoints) >= Integer.parseInt(integra)){
            jazUserIntegralDO.setIntegralDetail("-"+String.valueOf(Integer.parseInt(currentPoints)-Integer.parseInt(integra)));
            jazUserIntegralDO.setIntegralWay("系统扣减");
        }else {
            jazUserIntegralDO.setIntegralDetail("+"+String.valueOf(Integer.parseInt(integra)-Integer.parseInt(currentPoints)));
            jazUserIntegralDO.setIntegralWay("系统赠送");
        }
        try {
            jazUserIntegralDO.setIntegralTime(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        jazUserIntegralService.insert(jazUserIntegralDO);
        return Result.ok();
    }


    @Log(value = "删除用户",sysModule = 1,operationType = 2)
    @RequiresPermissions("sys:user:remove")
    @PostMapping("/remove")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<String> remove(Long id) {
        UserDO userDO = userService.selectById(id);
        if (userDO == null) {
            return Result.fail();
        }
        boolean b = userService.deleteById(id);
        //删除对应月嫂信息
        Wrapper<JazUserAuntDO> wrapper1 = new EntityWrapper<JazUserAuntDO>().orderBy("id", false);
        wrapper1.eq("sys_userid",id);
        jazUserAuntService.delete(wrapper1);
        //删除对应用户需求信息
        Wrapper<JazUserDemandDO> wrapper2 = new EntityWrapper<JazUserDemandDO>().orderBy("id", false);
        wrapper2.eq("sys_userid",id);
        jazUserDemandService.delete(wrapper2);
        //删除用户订单信息
        Wrapper<JazUserOrderDO> wrapper3 = new EntityWrapper<JazUserOrderDO>().orderBy("id", false);
        wrapper3.eq("initiate_id",id).or().eq("signing_id",id);
        jazUserOrderService.delete(wrapper3);
        //删除用户充值信息
        Wrapper<JazUserRechargeDO> wrapper4 = new EntityWrapper<JazUserRechargeDO>().orderBy("id", false);
        wrapper4.eq("sys_userid",id);
        jazUserRechargeService.delete(wrapper4);
        //删除用户合同信息
        Wrapper<JazSysContractDO> wrapper5 = new EntityWrapper<JazSysContractDO>().orderBy("id", false);
        wrapper5.eq("sys_userid",id);
        jazSysContractService.delete(wrapper5);
        //删除用户评价信息
        Wrapper<JazUserCommentDO> wrapper6 = new EntityWrapper<JazUserCommentDO>().orderBy("id", false);
        wrapper6.eq("comment_userid",id).or().eq("comment_userid",id);
        jazUserCommentService.delete(wrapper6);
        //删除用户积分信息
        Wrapper<JazUserIntegralDO> wrapper10 = new EntityWrapper<JazUserIntegralDO>().orderBy("id", false);
        wrapper10.eq("sys_userid",id);
        jazUserIntegralService.delete(wrapper10);
        //删除用户收藏信息
        Wrapper<JazUserCollectDO> wrapper11 = new EntityWrapper<JazUserCollectDO>().orderBy("id", false);
        wrapper11.eq("sys_userid",id);
        jazUserCollectService.delete(wrapper11);
        //删除用户签到信息
        Wrapper<JazUserSignInDO> wrapper12 = new EntityWrapper<JazUserSignInDO>().orderBy("id", false);
        wrapper12.eq("sys_userid",id);
        jazUserSignInService.delete(wrapper12);
        if(b){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }



    @GetMapping("/marketUserList")
    @ResponseBody
    public Result<?> marketUserList() {
        Map map = new HashMap<String,Object>();
        map.put("name","市场部");
        List<Map> mapList = new ArrayList<Map>();
        Map map1 = new HashMap<String,Object>();
        map1.put("name","市场一部");
        Map map2 = new HashMap<String,Object>();
        map2.put("name","市场二部");
        Long roleId1=1386577149715402754L;//市场一部角色ID,直接写死id,提高效率
        Long roleId2=1386577245253259266L;//市场二部角色ID
        List<UserRoleDO> userRoleDOS1 = userRoleService.findByKv("roleId",roleId1);
        List<UserRoleDO> userRoleDOS2 = userRoleService.findByKv("roleId",roleId2);
        List<UserDO> userDOS1 = new ArrayList<UserDO>();
        List<UserDO> userDOS2= new ArrayList<UserDO>();
        List<Map> userMapList1 = new ArrayList<Map>();
        List<Map> userMapList2 = new ArrayList<Map>();
        for(UserRoleDO userRoleDO : userRoleDOS1){
            Map userMap = new HashMap<String,String>();
            userMap.put("name",userService.selectById(userRoleDO.getUserId()).getName());
            userMapList1.add(userMap);
        }
        for(UserRoleDO userRoleDO : userRoleDOS2){
            Map userMap = new HashMap<String,String>();
            userMap.put("name",userService.selectById(userRoleDO.getUserId()).getName());
            userMapList2.add(userMap);
        }
        map1.put("children",userMapList1);
        map2.put("children",userMapList2);
        mapList.add(map1);
        mapList.add(map2);
        map.put("children",mapList);
        return Result.ok(map);
    }

    @RequiresPermissions("sys:user:edit")
    @Log(value = "更新用户",sysModule = 1,operationType = 3)
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result<String> updatePeronal(UserDO user) {
        userService.updatePersonal(user);
        return Result.ok();
    }

    @PostMapping("/exist")
    @ResponseBody
    boolean exist(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exist(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }


    @PostMapping("/resetPwd")
    @ResponseBody
    Result<String> resetPwd(UserVO userVO) {
        userService.resetPwd(userVO, getUser());
        return Result.ok();
    }

    @RequiresPermissions("sys:user:resetPwd")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result<String> adminResetPwd(UserVO userVO) {
        userService.adminResetPwd(userVO);
        return Result.ok();

    }

    @RequiresPermissions("sys:user:add")
    @Log(value = "审核",sysModule = 1,operationType = 3)
    @PostMapping("/review")
    @ResponseBody
    Result<String> check(@RequestParam("ids[]") Long[] ids,Integer state  ,String remark) {

        //查询字典:消息模板
        DictDO dic = null;
        String valStr = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (state == 2){
            dic = dictService.findOneByKv("type" , "check_no_pass");
            valStr = dic.getValue().replace("{value4}" , remark);
        }else{
            dic = dictService.findOneByKv("type" , "check_pass");
            valStr = dic.getValue();
        }
        valStr =  valStr.replace("{value1}" , "个人信息");
        valStr = valStr.replace("{value2}" , this.getUser().getUsername());
        valStr = valStr.replace("{value3}" , formatter.format(new Date()));

        for (Long id : ids){
            UserDO user = userService.selectById(id);
            user.setState(state);

            MsgDO msg = new MsgDO();
            if (state == 1){
                msg.setTitle("您的个人信息审核通过！");
                user.setRemark("");
            }else {
                msg.setTitle("您的个人信息审核未通过！");
                user.setRemark(remark);
            }
            msg.setContent(valStr);
            msg.setCreaterId(this.getUserId());
            msg.setCreaterDate(new Date());
            msg.setType(1);
            msg.setMsgType(0);
            msg.setUserId(id);
            msg.setState(0);
            if (userService.updateById(user)) {


                //------------------------订阅消息模块结束-----------------------------\

            }

        }
        return Result.ok();
    }


    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.selectById(getUserId());
        model.addAttribute("user", userDO);
        List<DictDO> hobbyList = dictService.getHobbyList(userDO);
        model.addAttribute("hobbyList", hobbyList);
        List<DictDO> sexList = dictService.getSexList();
        model.addAttribute("sexList", sexList);
        return prefix + "/personal";
    }

    @GetMapping("/adminMessage")
    String adminMessage(Model model, String state) {
        model.addAttribute("state", state);
        return prefix + "/adminMessage";
    }


    @ResponseBody
    @PostMapping("/uploadImg")
    Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap<>();
        result = userService.updatePersonalImg(file, avatar_data, getUserId());
        return Result.ok(result);
    }



    @GetMapping("/msgList")
    @ResponseBody
    Result<?> msgList(int current, int number, String state, String type) {
        UserDO user = this.getUser();
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        map.put("type", type);
        Page<MsgDO> page = msgService.selMsgPage(current, number, map);
        List<MsgDO> list = page.getRecords();
        for (MsgDO msg : list) {
            msg.setUserName(user.getUsername());
            UserDO user1 = userService.selectById(msg.getCreaterId());
            msg.setCreaterName(user1.getUsername());
        }
        page.setRecords(list);
        return Result.ok(page);
    }



    @GetMapping("/updateState")
    @ResponseBody
    Result<?> updateState(Long id) {
        MsgDO msg = msgService.selectById(id);
        msg.setState(2);
        msgService.updateById(msg);
        return Result.ok();
    }



    @GetMapping("/unreadNum")
    @ResponseBody
    Result<?> unreadNum(String type) {
        if (getUser() != null) {
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", this.getUserId(), "type", type);
            return Result.ok(msg.size());
        } else {
            return Result.ok(0);
        }

    }
}
